<template>
	<view class="v-switch" :class="{ 'is-disabled': disabled }" @click="toggleSwitch" :style="{ width: trackWidth, height: trackHeight }">
		<view class="switch-track" :style="trackStyle">
			<view class="switch-thumb" :style="thumbStyle">
				<v-min-loading
					v-model:value="props.loading"
					type="customize"
					:customize-color="props.loadingCustomizeColor"
					:vacancy-color="props.loadingVacancyColor"
				></v-min-loading>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { computed,inject } from 'vue';

/**
 * v-switch		开关
 * value	默认值:false		可选值:false关、true开
 * disabled	默认值:false		可选值:false不禁用、true禁用
 * activeColor		开启颜色
 * inactiveColor	关闭颜色
 * size				大小
 * loading			是否加载
 * loadingCustomizeColor	加载圈自定义颜色
 * loadingVacancyColor		加载圈缺口自定义颜色
 */
const props = defineProps({
	value: {
		type: Boolean,
		default: false
	},
	disabled: {
		type: Boolean,
		default: false
	},
	activeColor: {
		type: String,
		default: '#4cd964'
	},
	inactiveColor: {
		type: String,
		default: '#ebedf0'
	},
	size: {
		type: [String, Number],
		default: 'medium'
	},
	loading: {
		type: Boolean,
		default: false
	},
	loadingCustomizeColor: {
		type: String,
		default: "#969696"
	},
	loadingVacancyColor: {
		type: String,
		default: '#fff'
	}
});

const emit = defineEmits(['update:value']);
const config = inject<any>('config');
// 尺寸计算
const sizeMap = {
	small: 40,
	medium: 50,
	large: 60
};

const trackWidth = computed(() => {
	if (typeof props.size === 'number') return `${props.size}px`;
	return `${sizeMap[props.size] || sizeMap.medium}px`;
});

const trackHeight = computed(() => {
	const baseSize = typeof props.size === 'number' ? props.size : sizeMap[props.size] || sizeMap.medium;
	return `${baseSize * 0.5}px`;
});

// 滑块样式
const thumbStyle = computed(() => ({
	transform: `translateX(${props.value ? 'calc(100% - -5rpx)' : '4rpx'})`,
	width: `calc(${trackHeight.value} - 8rpx)`,
	height: `calc(${trackHeight.value} - 8rpx)`
}));

// 轨道样式
const trackStyle = computed(() => ({
	backgroundColor: props.value ? props.activeColor : props.inactiveColor,
	opacity: props.disabled ? 0.6 : 1
}));

// 切换状态
const toggleSwitch = () => {
	if (props.disabled) return;
	emit('update:value', !props.value);
};
</script>

<style lang="scss">
.v-switch {
	position: relative;
	display: inline-block;
	vertical-align: middle;
	cursor: pointer;
	transition: all 0.3s;

	&.is-disabled {
		cursor: not-allowed;
		opacity: v-bind("config.opacity.disabled");
	}

	.switch-track {
		position: relative;
		width: 100%;
		height: 100%;
		border-radius: 100px;
		background-color: v-bind("config.VSwitch.backgroundColor");
		transition: all 0.3s;
	}

	.switch-thumb {
		display: flex;
		position: absolute;
		top: 4rpx;
		background-color:  v-bind("config.backgroundColor.reversal");
		border-radius: 50%;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
		transition: all 0.3s cubic-bezier(0.3, 0.85, 0.5, 1);
	}
}
</style>
